package A003_NagrajObraz;



import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Insets;
import java.awt.Label;
import java.awt.MouseInfo;
import java.awt.PointerInfo;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Locale;

import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSpinner;
import javax.swing.JTextArea;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.border.EtchedBorder;
import javax.swing.border.MatteBorder;
import javax.swing.border.TitledBorder;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.filechooser.FileNameExtensionFilter;

import A003_NagrajObraz.OsCheck.OSType;


public class OREKOne implements  ActionListener, WindowListener, KeyListener {
		
	/**
	 * 
	 */
	
	public JDialog dialog;
	private Frame owner;
	private transient LinkedList<BufferedImage> iTMPObrazow = null;
	private transient HashMap<String, LinkedList<BufferedImage>> iBibloteka;
	private String iPathDefoult = "";
	JFileChooser chooser;
	String pathTemp = "/Users/tom/Desktop/test";

		
	private JSpinner iCzasProbki;
	int iczasprobki = 20;
	
	private JPanel iRamka_obraz;
	private JPanel iP_Obraz;
	private JPanel panel_1;
	private JPanel iParm1; //parametry szerokos pobieranego obrazka
	private JPanel panel_info;

	private JButton butnGOTOWOSC;
	private JButton btnNAGRYWAJ;
	private JButton btnReset;
	private JButton btnZapisz_1;
	
	private JButton btnSortuj;
	
	private JSpinner iWysokoscOb;
	private JSpinner iSzerokoscOb;
	private JLabel lblPOSort;

	private JLabel lblPrzedSort;
	private JButton btnWczytaj;
	
	private boolean iGotowyDoNagrywania=false;
	private boolean NAGRYWAM=false;
	private Robot rob;
	private BufferedImage iBuf; // zrzut spod kursorap
	private Image scaledImage;
	private Timer timer; //czestotliwosc probek
	public JTextArea log;

	private Component horizontalStrut_1;

	public OREKOne() {
		iTMPObrazow = new LinkedList<BufferedImage>(); // pezchowuje temObrazkow
		iBibloteka = new HashMap<String, LinkedList<BufferedImage>>(); // przechowuje kolekce z temObrazow
				
		if (OSType.MacOS == OsCheck.getOperatingSystemType()){
			iPathDefoult = "002-DoFi/SET/MAC/SZUKANE/";
			System.out.println("ścieżka " + iPathDefoult);

		} else if (OSType.Windows == OsCheck.getOperatingSystemType()) {
			iPathDefoult = "002-DoFi/SET/PC/SZUKANE/";
		}

		
		try {
			rob = new Robot();
		} catch (AWTException e) {
			e.printStackTrace();
		}

		try {
			String path = new java.io.File("..").getCanonicalPath();
				System.out.println("PATH \n" + path);
			//this.buf = ImageIO.read(new File(path+"/002-DoFi/src/NagrywarkaObrazkow/iKatObraz/centerConf.bmp"));
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize(Container parent, String title) {
		
		owner = null;
		if (parent instanceof Frame) owner = (Frame) parent;
		else owner = (Frame) SwingUtilities.getAncestorOfClass(Frame.class, parent);
		
		if (dialog == null || dialog.getOwner()!=owner){
			dialog = new JDialog(owner, true);
		}
		
		dialog = new JDialog();
		dialog.getContentPane().setLocale(new Locale("pl"));
		dialog.setAlwaysOnTop(true);

		dialog.setTitle(title);
		dialog.setBounds(100, 100, 256, 552);
		dialog.getContentPane().setLayout(null);

		iRamka_obraz = new JPanel();
		iRamka_obraz.setBounds(5, 6, 156, 156);
		iRamka_obraz.setBorder(new MatteBorder(3, 3, 3, 3, (Color) new Color(0, 0, 0)));
		iRamka_obraz.setBackground(Color.DARK_GRAY);
		iRamka_obraz.setLayout(null);
		dialog.getContentPane().add(iRamka_obraz);
		
		dialog.addWindowListener(new WindowListener() {
			
			@Override
			public void windowOpened(WindowEvent e) {	}
			
			@Override
			public void windowIconified(WindowEvent e) {	}
			
			@Override
			public void windowDeiconified(WindowEvent e) {	}
			
			@Override
			public void windowDeactivated(WindowEvent e) {	}
			
			@Override
			public void windowClosing(WindowEvent e) {
				System.out.println("close");
				System.exit(0);
				SwingUtilities.getWindowAncestor(dialog).dispose();
			}
			
			@Override
			public void windowClosed(WindowEvent e) {	}
			
			@Override
			public void windowActivated(WindowEvent e) {	}
		});
		
		iP_Obraz = new iObraz();
		iRamka_obraz.add(iP_Obraz);

		panel_1 = new JPanel();
		panel_1.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				System.out.println(e.getKeyChar());

			}
		});
		
		iParm1 = new JPanel();
		iParm1.setBounds(5, 174, 156, 87);
		dialog.getContentPane().add(iParm1);
		iParm1.setBorder(new TitledBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null), "", TitledBorder.CENTER, TitledBorder.TOP, null, null));
		iParm1.setLayout(new GridLayout(0, 3, 0, 0));
		
		
		iSzerokoscOb = new JSpinner();
		iSzerokoscOb.setToolTipText("Szeroko\u015B\u0107 pr\u00F3bki 1-301px");
		iSzerokoscOb.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				//iWysokoscOb.setValue((long) iSzerokoscOb.getValue());
			}
		});
		
		horizontalStrut_1 = Box.createHorizontalStrut(20);
		iParm1.add(horizontalStrut_1);
		iSzerokoscOb.setModel(new SpinnerNumberModel(new Long(3), new Long(1), new Long(701), new Long(1)));
		iParm1.add(iSzerokoscOb);
		
		
		iWysokoscOb = new JSpinner();
		iWysokoscOb.setToolTipText("Wysoko\u015B\u0107 pr\u00F3bki 1-301px");
		iWysokoscOb.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				//iSzerokoscOb.setValue((long) iWysokoscOb.getValue());
			}
		});
		
		JLabel lblSzer_1 = new JLabel("szer.");
		lblSzer_1.setHorizontalAlignment(SwingConstants.CENTER);
		lblSzer_1.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblSzer_1);
		
		Component horizontalStrut_2 = Box.createHorizontalStrut(20);
		iParm1.add(horizontalStrut_2);
		iWysokoscOb.setModel(new SpinnerNumberModel(new Long(3), new Long(1), new Long(701), new Long(1)));
		iWysokoscOb.setFont(new Font("Tahoma", Font.BOLD, 11));
		iParm1.add(iWysokoscOb);
		
		JLabel lblWys = new JLabel("wys.");
		lblWys.setHorizontalAlignment(SwingConstants.CENTER);
		lblWys.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblWys);
		
		Component horizontalStrut_3 = Box.createHorizontalStrut(20);
		iParm1.add(horizontalStrut_3);
		
		iCzasProbki = new JSpinner();
		iCzasProbki.addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent e) {
				iczasprobki = (int)iCzasProbki.getValue();
				timer.setDelay(iczasprobki);
			}
		});
		iCzasProbki.setModel(new SpinnerNumberModel(new Integer(0), new Integer(0), new Integer(500), new Integer(1)));
		iCzasProbki.setToolTipText("Szybko\u015B\u0107 probki obrazu 10-500ms");
		iParm1.add(iCzasProbki);
		
		JLabel lblms = new JLabel("ms");
		lblms.setHorizontalAlignment(SwingConstants.CENTER);
		lblms.setFont(new Font("Dialog", Font.PLAIN, 11));
		iParm1.add(lblms);
		panel_1.setBounds(5, 262, 225, 95);
		dialog.getContentPane().add(panel_1);
		panel_1.setLayout(new GridLayout(0, 2, 0, 0));
		
		
		butnGOTOWOSC = new JButton("");
		butnGOTOWOSC.setMnemonic(KeyEvent.VK_KP_LEFT);
		final ImageIcon ikona1 = 
				new ImageIcon(OREKOne.class.getResource
						("/A003_NagrajObraz/Images/play20x20.png"));
		final ImageIcon ikona2 = 
				new ImageIcon(OREKOne.class.getResource
						("/A003_NagrajObraz/Images/stop20x20.png"));
		if (iGotowyDoNagrywania == false)
			{butnGOTOWOSC.setIcon(ikona1);}
		else if (iGotowyDoNagrywania == true)
			{butnGOTOWOSC.setIcon(ikona2);}
		
		dialog.getRootPane().setDefaultButton(butnGOTOWOSC);
		
		butnGOTOWOSC.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				
				if (iGotowyDoNagrywania == false){
					butnGOTOWOSC.setIcon(ikona2);
					//--------------
					iGotowyDoNagrywania = true;
					btnNAGRYWAJ.setEnabled(true);
				} else{ // if is true
					if (iTMPObrazow.size() > 0){
						
					}
					butnGOTOWOSC.setIcon(ikona1);
					iGotowyDoNagrywania = false;
					//--------------
					NAGRYWAM = false;
					// akcaj jesli do sotownia jest lista
					if  (NAGRYWAM == false && iTMPObrazow.size()>0){
					}
					btnNAGRYWAJ.setEnabled(false);
				}
				
				if (!iGotowyDoNagrywania && !NAGRYWAM){ //sterowanie klawiszami
					dialog.getRootPane().setDefaultButton(butnGOTOWOSC);
				} else if (iGotowyDoNagrywania && !NAGRYWAM){
					dialog.getRootPane().setDefaultButton(btnNAGRYWAJ);
				} else dialog.getRootPane().setDefaultButton(butnGOTOWOSC);
				
			}
		});	
		
		
		butnGOTOWOSC.setToolTipText("Naci\u015Bnij \"ENTER\" zablokujesz ramk\u0119 podgladu");
		panel_1.add(butnGOTOWOSC);
		
		btnNAGRYWAJ = new JButton("NAGRYWAJ");
		btnNAGRYWAJ.setEnabled(false);
		btnNAGRYWAJ.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
				if (iGotowyDoNagrywania == false){
					return;
				}
				NAGRYWAM = true;
				btnNAGRYWAJ.setEnabled(false);
			
				if (!iGotowyDoNagrywania && !NAGRYWAM){ //sterowanie klawiszami
					dialog.getRootPane().setDefaultButton(butnGOTOWOSC);
				} else if (iGotowyDoNagrywania && !NAGRYWAM){
					dialog.getRootPane().setDefaultButton(btnNAGRYWAJ);
				} else dialog.getRootPane().setDefaultButton(butnGOTOWOSC);
			}
			
		});



		btnNAGRYWAJ.setToolTipText("Naci\u015Bnij \"S\" odblokujesz ramk\u0119 podgladu");
		panel_1.add(btnNAGRYWAJ);
		
		btnReset = new JButton("RESET");
		btnReset.setToolTipText("resetuje bufory z obrazami");
		btnReset.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				if (iGotowyDoNagrywania == false && NAGRYWAM ==false){
					Reset();
				}
			}
		});
		panel_1.add(btnReset);
		
		btnZapisz_1 = new JButton("ZAPISZ");
		btnZapisz_1.setToolTipText("zapisujesz obrazki zawarte w buforze");
		btnZapisz_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
			}
		});
		btnZapisz_1.addMouseListener(new MouseAdapter() {
			public void mousePressed(MouseEvent arg0) {
				iZapisz();
			}
			
			private void iZapisz() {
				
				
				System.out.println("Zapisuje elementow " + iTMPObrazow.size());
				if (iTMPObrazow.size() == 0) return;
				
				 Object[] options = { "OK", "NIE" };
				 
					int JP = JOptionPane.showOptionDialog(null, "Chcesz SORTOWAC przed zapisem", "Uwaga przed ZAPISANIEM",
					             JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
					             null, options, options[0]);
					if (JP == JOptionPane.CANCEL_OPTION){
						return;
					}
					
					if (JP == JOptionPane.OK_OPTION){
						try {
							iSortuj();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					
				Iterator<BufferedImage> it = iTMPObrazow.iterator();
				BufferedImage buf = null;
				File iPathFolder = null;
				int licz = 0;
				
				JFileChooser chooser = new JFileChooser();
			   // chooser.setCurrentDirectory(new java.io.File (iInitLinki.iGlobalPathSET + iInitLinki.iKatSys + "SZUKANE/"));
			    chooser.setCurrentDirectory(new java.io.File (pathTemp));

				chooser.setFileFilter(new FileNameExtensionFilter("BMP", "bmp"));

				int result = chooser.showSaveDialog(null);
			    
				if (result == JFileChooser.CANCEL_OPTION){
					Reset();
					return;
				}
				    
				//File file = chooser.getSelectedFile();
			    if (result == JFileChooser.APPROVE_OPTION) { 
			    	iPathFolder = chooser.getCurrentDirectory();
			      System.out.println("getCurrentDirectory(): " +  iPathFolder);
			      System.out.println("getSelectedFile() : " +  chooser.getSelectedFile());
			      }
			    else { System.out.println("No Selection ");
			      }
			    
			    LinkedList<int[][]> tmpLL = new LinkedList<int[][]>();
			    
			    while (it.hasNext()){
			    	buf =  (BufferedImage) it.next();
			    	File outputfile = new File(chooser.getSelectedFile() + "_" + licz++ +".bmp");
				    try {
						ImageIO.write(buf, "bmp", outputfile);
					} catch (IOException e) {
						e.printStackTrace();
					}
				    
			    	iLog("" + outputfile.getAbsoluteFile().getName()); 
			    	
			    	// dla zapisu calosci do int
			    	
			    	int [][] tmpbufINT = new int [buf.getWidth()][buf.getHeight()];
			    	
			    	for (int y = 0; y < buf.getHeight(); y++){
			    		for (int x = 0; x< buf.getWidth(); x++){
			    			tmpbufINT [x][y] = buf.getRGB(x, y);
			    		}
			    	}
			    	
			    	tmpLL.push(tmpbufINT);
			    }
			    //serializacja
			    //http://stackoverflow.com/questions/15058663/how-to-serialize-an-object-that-includes-bufferedimages
			    
		    	 String path = iPathFolder + "/" +chooser.getSelectedFile().getName() + ".ser";
		    	 System.out.println("Zapis " + path);
		    	 		    	 
		    	 try
		         {
		             FileOutputStream fileOut = new FileOutputStream(path);
		             ObjectOutputStream out = new ObjectOutputStream(fileOut);
		             out.writeObject(tmpLL);
		             out.close();
		             fileOut.close();
		             System.out.printf("Serialized data is saved in /tmp/employee.ser");
		          }catch(IOException i)
		          {
		              i.printStackTrace();
		          }
		    	 
			    Reset();

			}
			
		});
		
		btnSortuj = new JButton("SORTUJ");
		btnSortuj.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				try {
					iSortuj();
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		btnSortuj.setToolTipText("czysci bufory z takich samych obrazow");
		panel_1.add(btnSortuj);
		
		btnWczytaj = new JButton("WCZYTAJ");
		btnWczytaj.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				iWczytaj();
			}
			
			@SuppressWarnings("unchecked")
			private void iWczytaj() {
				
				JFileChooser chooser = new JFileChooser();
			    chooser.setCurrentDirectory(new java.io.File (pathTemp));
					
			     chooser.setFileFilter(new FileNameExtensionFilter("ser", "ser"));

			     int rezultat = chooser.showOpenDialog(null);
			     
					if (rezultat == JFileChooser.CANCEL_OPTION){
						return;
					}
					
				LinkedList<int[][]> tmpLL = new LinkedList<int[][]>(); 
			      
				try{
					String path = chooser.getCurrentDirectory() + "/" +chooser.getSelectedFile().getName();
			    	System.out.println("Odczyt " + path);
			    	 
			      FileInputStream fis = new FileInputStream(path);
			      ObjectInputStream ois = new ObjectInputStream(fis);
			      tmpLL  = (LinkedList<int[][]>) ois.readObject();

			      ois.close();

			      System.out.println (tmpLL);

			  } catch (FileNotFoundException e) {e.printStackTrace();
			  } catch (IOException e) {e.printStackTrace();
			     } catch (ClassNotFoundException e) {e.printStackTrace();
			     }
				
				if (!iTMPObrazow.isEmpty()){
					if(!Reset()) return;
				}
			
				if (!tmpLL.isEmpty()){
					iLog("Wczytuję elementów "+ tmpLL.size());
					int [][] first = tmpLL.getFirst();
					iSzerokoscOb.setModel(new SpinnerNumberModel(new Long(first.length), new Long(1), new Long(701), new Long(1)));
					iWysokoscOb.setModel(new SpinnerNumberModel(new Long(first[0].length), new Long(1), new Long(701), new Long(1)));
				}
				
				BufferedImage tmpBuf;
				for (int[][] to : tmpLL){
					tmpBuf = new BufferedImage(to.length, to[0].length, iBuf.getType());
					
					for (int y = 0; y < to[0].length; y++){
						for (int x = 0; x < to.length; x++){
							tmpBuf.setRGB(x, y, to[x][y]);
						}
					}
					iTMPObrazow.push(tmpBuf);
				}
				
				System.out.println (iTMPObrazow.toString());
			}
			
		});
		

		btnWczytaj.setToolTipText("mozesz wczytac inne schematy tej samej wielkości obrazki co w buforze");
		panel_1.add(btnWczytaj);
		panel_1.add(btnZapisz_1);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBounds(5, 360, 245, 165);
		panel_2.setLayout(new GridLayout(0, 1, 0, 0));
		dialog.getContentPane().add(panel_2);
		
		log = new JTextArea();
        log.setMargin(new Insets(5,5,5,5));
        log.setEditable(false);
		panel_2.add(log);
        JScrollPane logScrollPane = new JScrollPane(log);
        panel_2.add(logScrollPane);
        
        panel_info = new JPanel();
        panel_info.setBounds(166, 6, 84, 95);
        dialog.getContentPane().add(panel_info);
        panel_info.setLayout(new GridLayout(3, 1, 0, 0));
        
        lblPrzedSort = new JLabel("0");
        lblPrzedSort.setHorizontalAlignment(SwingConstants.CENTER);
        panel_info.add(lblPrzedSort);
        
        lblPOSort = new JLabel("0");
        lblPOSort.setFont(new Font("Lucida Grande", Font.PLAIN, 28));
        lblPOSort.setHorizontalAlignment(SwingConstants.CENTER);
        panel_info.add(lblPOSort);
        
        JLabel lblBibloteka = new JLabel("0");
        lblBibloteka.setHorizontalAlignment(SwingConstants.CENTER);
        panel_info.add(lblBibloteka);

				
		timer = new Timer(iczasprobki, action);
		timer.start();
		
		dialog.setVisible(true);

	}
	int a = 0, b=0, sz=0, w=0; String text;
	private ActionListener action = new ActionListener() {
		public void actionPerformed(ActionEvent ae) {
			//System.out.println("starat");
			if(!iGotowyDoNagrywania){
				a = igetCurrentPosX();
				b = igetCurrentPosY();
			}
			if(!NAGRYWAM){
				sz = (int)(long)iSzerokoscOb.getValue();
				w  = (int)(long)iWysokoscOb.getValue();				
			}
			
			if(NAGRYWAM){
				btnReset.setEnabled(false);
				btnWczytaj.setEnabled(false);
				btnZapisz_1.setEnabled(false);
				btnSortuj.setEnabled(false);
				
			} else{
				btnReset.setEnabled(true);
				btnWczytaj.setEnabled(true);
				btnZapisz_1.setEnabled(true);
				btnSortuj.setEnabled(true);
			}
			
			iBuf = rob.createScreenCapture(new Rectangle (a-sz/2, b-w/2, sz, w));
			if (NAGRYWAM == true && iTMPObrazow != null) {
				iTMPObrazow.add(iBuf);
			}
			lblPrzedSort.setText(""+iTMPObrazow.size());

			if (iTMPObrazow == null){
				text = "00pu"; 
			} else text = ""+iTMPObrazow.size();
						
			if (!iTMPObrazow.isEmpty()) {
				iSzerokoscOb.setEnabled(false);
				iWysokoscOb.setEnabled(false);
			} else {
				iSzerokoscOb.setEnabled(true);
				iWysokoscOb.setEnabled(true);
			}
			
			panel_info.repaint();
			iRamka_obraz.repaint();
		}
	};
	//============================================================================
	private int igetCurrentPosX(){
		PointerInfo pointer = MouseInfo.getPointerInfo();
//		System.out.print("POZYCJA MOUSA X: " + pointer.getLocation().x + " ");
		return pointer.getLocation().x;
	}
	private int igetCurrentPosY(){
		PointerInfo pointer = MouseInfo.getPointerInfo();
//		System.out.println("POZYCJA MOUSA Y: " + pointer.getLocation().y);
		return pointer.getLocation().y;
	}
	

	protected boolean Reset() {
		 Object[] options = { "OK", "CANCEL" };
		 
		int JP = JOptionPane.showOptionDialog(null, "OK zresetujesz bufor", "Uwaga RESET",
		             JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
		             null, options, options[0]);
		
		if (JP == JOptionPane.CANCEL_OPTION){
			return false;
		}
		
		if (JP == JOptionPane.OK_OPTION){
			iTMPObrazow.clear();
		}
		
		lblPOSort.setText(""+ 0);
		
		return true;
	}
	

	class iObraz extends JPanel {
		/**
		 * 
		 */
		private static final long serialVersionUID = 1L;
		
		int wFrameObraz;
		int hFrameObraz;
		
		public iObraz() {
			super();
	
			setBackground(Color.gray);
			setBounds(new Rectangle(10, 11, 136, 134));
			setBorder(BorderFactory.createLineBorder(Color.black));
			setLayout(new FlowLayout(FlowLayout.CENTER)); 
		}
		
		@Override
		protected void paintComponent(Graphics g) {
			super.paintComponent(g);
	
			wFrameObraz = iP_Obraz.getSize().width;
			hFrameObraz = iP_Obraz.getSize().height;
			if ( iBuf !=  null ){
				scaledImage = (iBuf.getScaledInstance(wFrameObraz, wFrameObraz, (Image.SCALE_AREA_AVERAGING)));
				g.drawImage(scaledImage, 0, 0, null);
			}
		}
	}
			
		@Override
		public void windowOpened(WindowEvent e) {
			// TODO Auto-generated method stub
		}
		
		@Override
		public void windowClosing(WindowEvent e) {
			System.out.println("zmaykasz okno)");		
		}
		
		@Override
		public void windowClosed(WindowEvent e) {
			System.runFinalization();
			System.exit(0);
		}
		
		@Override
		public void windowIconified(WindowEvent e) {	}
		
		@Override
		public void windowDeiconified(WindowEvent e){	}
		
		@Override
		public void windowActivated(WindowEvent e) {	}
		
		@Override
		public void windowDeactivated(WindowEvent e) {	}
		
		/*@Override
		public void nativeKeyPressed(NativeKeyEvent arg0) {
				int a=arg0.getKeyCode();
				System.out.println("nacisniety klawisz-"+a+" "+arg0.getKeyText(a)+" "+ arg0.paramString());
				switch (a){
					case (KeyEvent.VK_MINUS):
						if(iczasprobki<=0)break; 
						iCzasProbki.setValue(iczasprobki-10);
						break;
					case (KeyEvent.VK_EQUALS):
						if(iczasprobki>0)break;
						iCzasProbki.setValue(iczasprobki+10);
						break;
					case KeyEvent.VK_ADD: 
						if ((long)iWysokoscOb.getValue()<701 && ((long)iWysokoscOb.getValue())>=3) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+1);
						if ((long)iWysokoscOb.getValue()<701 && ((long)iWysokoscOb.getValue())<3) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+1);
						break;
					case KeyEvent.VK_SUBTRACT: 
						if ((long)iWysokoscOb.getValue()> 5 && ((long)iWysokoscOb.getValue())>=3) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())-2);
						if ((long)iWysokoscOb.getValue()> 5 && ((long)iWysokoscOb.getValue())< 3) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())-2);
						break;
					case KeyEvent.VK_LEFT: 
						System.out.println("LEFT)");
						if ((long)iWysokoscOb.getValue()<701 && ((long)iWysokoscOb.getValue())>=3) 
							iWysokoscOb.setValue(((long)iWysokoscOb.getValue())+1);
						break;
					case KeyEvent.VK_RIGHT: 
						break;	
					case KeyEvent.VK_ESCAPE: 
						GlobalScreen.unregisterNativeHook();
						System.runFinalization();
						System.exit(2);
						break;
				}
		}*/
		

		
		@Override
		public void actionPerformed(ActionEvent e) {	}
		
		
		@Override
		public void keyPressed(KeyEvent e) {
			System.out.println("NACISK " + e.getKeyChar());
			
		}

		@Override
		public void keyReleased(KeyEvent e) {
			System.out.println("NACISK " + e.getKeyChar());
			
		}

		@Override
		public void keyTyped(KeyEvent e) {
			System.out.println("NACISK " + e.getKeyChar());
			
		}
		

		public void iLog(String log) {
			this.log.append(""+log +"\n");
		}
		
		/**
		 * Laduje do LinkedList
		 * @param buf
		 */
		public void iIN (BufferedImage buf){
			if (iTMPObrazow == null) {
				iTMPObrazow = new LinkedList<BufferedImage>();
			}
			iTMPObrazow.add(buf);
		}
		
		/**
		 * Usuwa zbędne elmenty z tablicy
		 * @throws IOException 
		 */
		int wilkoscIN;
		int wielkoscOUT;
		public void iSortuj() throws IOException{
			
			if (iTMPObrazow == null || iTMPObrazow.size() == 0) return;
			
			wilkoscIN = iTMPObrazow.size();
			
			BufferedImage el1=null, el2=null;
			
			for (int a = 0; a < iTMPObrazow.size(); a++){
				for (int b = a+1; b < iTMPObrazow.size(); b++){
					
					
					el1 = iTMPObrazow.get(a);
					el2 = iTMPObrazow.get(b);
					
					
					if (el1 != null && el2 != null) {
						if (el1.getWidth() != el2.getWidth() || el1.getHeight() != el2.getHeight()) {
							JOptionPane.showConfirmDialog(dialog, "OBRAZY SĄ NIE ZGONE WIELKOŚCIOWO");
							Reset();
							return;
						}
						
						if (iPorownaj(el1, el2)) {
							iTMPObrazow.remove(b);
						}; 
					}				
				}
					iLog("ilosc obrazów po sortowniu.." + iTMPObrazow.size( ));
			}
			lblPOSort.setText(""+iTMPObrazow.size());
			
			if ( iTMPObrazow.size() != wilkoscIN) iSortuj();
			
			return;
		}
		
		//porownaj jesli true - to obrazy sa taki same
		private boolean iPorownaj (BufferedImage el1, BufferedImage el2){
			
			for (int y = 0; y < el1.getHeight(); y++){
				for (int x = 0; x < el1.getWidth(); x++){
					
					if (el1.getRGB(x, y) != el2.getRGB(x, y)) {
							return false;
					}
				}
			}
			
			return true;
		}
		
		/**
		 * Launch the application.
		 */
		public static void main(String[] args) {
			System.out.println("test");
				OREKOne window = new OREKOne();
				window.initialize(null, "NAGRYWARKA");
			System.out.println("test");

		}
}
